package phase1.part1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import phase1.part1.RecursiveDescender.Result;

/**
 * 
 * 
 * @author John Girata
 * @version Nov 17, 2012
 */
public class Driver {
	public static void main(String[] args) throws Exception {
		if (args.length != 2) {
			System.out.println("Usgae: java phase1.part1.Driver spec nfa");
			return;
		}

		buildNFA(args[0], args[1]);
	}

	public static void buildNFA(String spec, String nfa)
			throws FileNotFoundException {
		RecursiveDescender rd = new RecursiveDescender();
		Scanner scanner = new Scanner(new File(spec));
		State globalStart = new State();
		List<State> accepting = new ArrayList<>();

		boolean switchover = false;

		while (scanner.hasNext()) {
			String line = scanner.nextLine();

			if (line.isEmpty()) {
				switchover = true;
				continue;
			}

			if (line.charAt(0) == '%' && line.charAt(1) == '%') {
				continue;
			}

			Result result;

			if (switchover) {
				result = rd.processRegex(line);
			} else {
				result = rd.processCharClass(line);
			}

			if (result == Result.NEW_REGEX) {
				State lastStart = rd.getLastNFA();
				globalStart.addTransition(lastStart);
				State accept = RecursiveDescender.findAccepting(lastStart);
				accepting.add(accept);
				accept.setTokenClass(rd.getLastKey());
			}
		}

		int end = Integer.parseInt(new State().getLabel());
		PrintStream out = new PrintStream(nfa);
		out.print("STATES ");

		for (int i = 0; i < end; i++) {
			out.print(i + ",");
		}

		out.println(end);
		out.println("START " + globalStart.getLabel());
		
		for (State a : accepting) {
			out.println("ACCEPT " + a.getTokenClass() + " " + a.getLabel());
		}

		globalStart.print(out);
	}
}
